package com.kobeliu.netty.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MessagePublisher {

    //定义交换机
    public static final String EXCHANGE_MSG = "exchange_chat_msg";
    //定义队列
    public static final String QUEUE_MSG = "queue_chat_msg";
    //定义路由key
    public static final String SAVE_MSG_ROUTING_KEY = "imooc.chat.msg.save.do";

    public static void saveMessageByMQ(String msg) throws IOException, TimeoutException {

        //建立连接
        ConnectionFactory factory = new ConnectionFactory();
        //线上
        factory.setHost("192.168.6.83");
        //本地
//        factory.setHost("192.168.10.70");
        factory.setPort(5672);
        factory.setVirtualHost("imooc-msg");
        factory.setUsername("kobeLiu");
        factory.setUsername("88702611");

        //建立连接
        Connection connection = factory.newConnection();

        //创建通道
        Channel channel = connection.createChannel();

        String queueName = QUEUE_MSG;
        /**
         * 是否持久化
         * 是否独占队列
         * 不用的时候是否删除
         */
        channel.queueDeclare(queueName,true,false,false,null);

        // 发送消息
        channel.basicPublish(EXCHANGE_MSG,SAVE_MSG_ROUTING_KEY,null,msg.getBytes());

        //关闭通道和连接
        channel.close();
        connection.close();
    }
}
